package net.keebook.webapp.ws;

import javax.ejb.Stateless;
import javax.inject.Inject;

import net.keebook.webapp.dao.KeeBookDao;
import net.keebook.webapp.dao.UserDao;
import net.keebook.webapp.entity.KeeBook;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.BCrypt;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;


@Stateless
public abstract class WebService {
	public static final String ERROR_RESPONSE = "{'success': false, 'authSuccess': false}";
	protected static final String AUTH_PASSWORD = "password";
	protected static final String AUTH_SESSION = "session";
	
	@Inject
	private UserDao userDao;
	@Inject
	private KeeBookDao keeBookDao;
	
	protected String getResponse(JSONObject jsonObject) {
		return getResponse(jsonObject.toString());
	}
	
	protected String getResponse(String response) {
		Logger.getLogger(this.getClass()).trace("Sending JSON to client: " + response);
		return response;
	}
	
	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	protected JSONObject getInput(String jsonString) {
		JSONObject input;
		try {
			input = new JSONObject(jsonString);
		} catch (JSONException e) {
			input = new JSONObject();
		}
		return input;
	}
	
	protected User authenticate(String username, String password) {
		return authenticate(username, password, AUTH_PASSWORD, null);
	}
	
	protected User authenticate(String username, String password, String auth, SessionModel sessionModel) {
		if (AUTH_PASSWORD.equals(auth)) {
			User user = getUserDao().getUserByUsername(username);
			if (user != null && user.getEnabled() && BCrypt.checkpw(password, user.getHashedPassword())) {
				return user;
			}
			return null;
		} else if (AUTH_SESSION.equals(auth) && sessionModel != null) {
			User user = null;
			if (sessionModel.getLoggedIn()) {
				user = getUserDao().get(sessionModel.getUserId());
				if (user != null && user.getEnabled()) {
					return user;
				}
			}
			return null;
		}
		return null;
	}
	
	protected KeeBook getKeeBook(String id, String checksum) {
		KeeBook keeBook = getKeeBookDao().get(id);
		if (keeBook == null || !keeBook.getKeyphraseChecksum().equals(checksum)) {
			return null;
		}
		return keeBook;
	}

	public KeeBookDao getKeeBookDao() {
		return keeBookDao;
	}

	public void setKeeBookDao(KeeBookDao keeBookDao) {
		this.keeBookDao = keeBookDao;
	}
}
